package com.xishu.task;

import com.xishu.config.Config;
import com.xishu.config.Constant;
import com.xishu.entity.payment.PaymentCheck;
import com.xishu.service.CommonService;
import com.xishu.service.LeaderService;
import com.xishu.service.PaymentCheckService;
import com.xishu.util.Tools;
import org.apache.logging.log4j.ThreadContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class PaymentTask implements Tools {
    private static Logger logger = LoggerFactory.getLogger(PaymentTask.class);
    private CommonService commonService = CommonService.getInstance();
    private Config config = Config.getInstance();


    /**
     * 每5秒执行一次校验
     *
     *
     * @throws Exception
     */
    @Scheduled(initialDelay = 5 * 1000, fixedDelay = 5 * 1000)
    public void action() {
        if (config.isWindows()) {
            return;
        }

        LeaderService leaderService = LeaderService.getInstance();
        if (!leaderService.elect()) {
            logger.info("elect failed");
            return;
        }

        ThreadContext.put(Constant.REQUEST_ID, "payment task");

        List<PaymentCheck> paymentCheckList = PaymentCheckService.getInstance().queryExpireCheck();

        for (PaymentCheck paymentCheck : paymentCheckList) {
            PaymentCheckService.getInstance().validPayment(paymentCheck);
        }
    }
}
